package com.freesky.provider.member.controller;

import com.freesky.common.dao.entity.Member;
import com.freesky.common.geetest.GeetestConfig;
import com.freesky.common.geetest.GeetestLib;
import com.freesky.common.pojo.DataTablesResult;
import com.freesky.common.pojo.Result;
import com.freesky.common.redis.IRedisTemplate;
import com.freesky.common.utils.ResultUtil;
import com.freesky.common.utils.reponse.JSONResponse;
import com.freesky.common.utils.reponse.JSONResponseDiretor;
import com.freesky.common.vo.VOCommon;
import com.freesky.common.vo.VOMember;
import com.freesky.common.vo.VOMemberLoginRegist;
import com.freesky.provider.member.service.IMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;


/**
 * @author Freesky
 * @date 2017/8/11
 */
@RestController
public class MemberController {
    @Autowired
    private IRedisTemplate redisTemplate;
    @Autowired
    private IMemberService memberService;

    @GetMapping(value = "/member/list")
    public DataTablesResult getMemberList(
            @RequestParam(value = "draw") int draw,
            @RequestParam(value = "start") int start,
            @RequestParam(value = "length") int length,
            @RequestParam(value = "searchKey") String searchKey,
            @RequestParam(value = "minDate") String minDate,
            @RequestParam(value = "maxDate") String maxDate,
            @RequestParam(value = "search[value]") String search,
            @RequestParam(value = "order[0][column]") int orderCol,
            @RequestParam(value = "order[0][dir]") String orderDir) {

        //获取客户端需要排序的列
        String[] cols = {"checkbox", "id", "username", "sex", "phone", "email", "address", "created", "updated", "state"};
        String orderColumn = cols[orderCol];
        //默认排序列
        if (orderColumn == null) {
            orderColumn = "created";
        }
        //获取排序方式 默认为desc(asc)
        if (orderDir == null) {
            orderDir = "desc";
        }
        if (!search.isEmpty()) {
            searchKey = search;
        }
        DataTablesResult result = memberService.getMemberList(draw, start, length, searchKey, minDate, maxDate, orderColumn, orderDir);
        return result;
    }

    @GetMapping(value = "/member/list/remove")
    public DataTablesResult getDelMemberList(
            @RequestParam(value = "draw") int draw,
            @RequestParam(value = "start") int start,
            @RequestParam(value = "length") int length,
            @RequestParam(value = "searchKey") String searchKey,
            @RequestParam(value = "minDate") String minDate,
            @RequestParam(value = "maxDate") String maxDate,
            @RequestParam(value = "search[value]") String search,
            @RequestParam(value = "order[0][column]") int orderCol,
            @RequestParam(value = "order[0][dir]") String orderDir) {

        //获取客户端需要排序的列
        String[] cols = {"checkbox", "id", "username", "sex", "phone", "email", "address", "created", "updated", "state"};
        String orderColumn = cols[orderCol];
        //默认排序列
        if (orderColumn == null) {
            orderColumn = "created";
        }
        //获取排序方式 默认为desc(asc)
        if (orderDir == null) {
            orderDir = "desc";
        }
        if (!search.isEmpty()) {
            searchKey = search;
        }
        DataTablesResult result = memberService.getRemoveMemberList(draw, start, length, searchKey, minDate, maxDate, orderColumn, orderDir);
        return result;
    }

    @GetMapping(value = "/member/count")
    public DataTablesResult getMemberCount() {

        return memberService.getMemberCount();
    }

    @GetMapping(value = "/member/count/remove")
    public DataTablesResult getRemoveMemberCount() {

        return memberService.getRemoveMemberCount();
    }

    @PostMapping(value = "/member/add")
    public void createMember(@ModelAttribute VOMember voMember) {
        memberService.addMember(voMember);
    }

    @PutMapping(value = "/member/stop/{id}")
    public JSONResponse stopMember(@PathVariable(value = "id") Long id) {

        Member member = memberService.alertMemberState(id, 0);
        return JSONResponseDiretor.buildSuccessJSONResponse(member);
    }

    @PutMapping(value = "/member/start/{ids}")
    public JSONResponse startMember(@PathVariable(value = "ids") Long[] ids) {

        for (Long id : ids) {
            memberService.alertMemberState(id, 1);
        }
        return JSONResponseDiretor.buildSuccessJSONResponse(null);
    }

    @PutMapping(value = "/member/remove/{ids}")
    public JSONResponse removeMember(@PathVariable(value = "ids") Long[] ids) {

        for (Long id : ids) {
            memberService.alertMemberState(id, 2);
        }
        return JSONResponseDiretor.buildSuccessJSONResponse(null);
    }

    @DeleteMapping(value = "/member/del/{ids}")
    public JSONResponse deleteMember(@PathVariable(value = "ids") Long[] ids) {

        for (Long id : ids) {
            memberService.deleteMember(id);
        }
        return JSONResponseDiretor.buildSuccessJSONResponse(null);
    }

    @PostMapping(value = "/member/change-password/{id}")
    public JSONResponse changeMemberPassword(@PathVariable(value = "id") Long id, @ModelAttribute VOMember voMember) {

        Member member = memberService.changePassMember(id, voMember);
        return JSONResponseDiretor.buildSuccessJSONResponse(member);
    }

    @PostMapping(value = "/member/update/{id}")
    public JSONResponse updateMember(@PathVariable(value = "id") Long id, @ModelAttribute VOMember voMember) {
        Member member = memberService.updateMember(id, voMember);
        return JSONResponseDiretor.buildSuccessJSONResponse(member);
    }

    @GetMapping(value = "/member/{id}")
    public Result<Member> getMemberById(@PathVariable(value = "id") Long id) {

        Member member = memberService.getMemberById(id);
        return new ResultUtil<Member>().setData(member);
    }

    @GetMapping(value = "/member/username")
    public Boolean validateUsername(@RequestParam(value = "username") String username) {
        if (memberService.getMemberByUsername(username) != null) {
            return false;
        }
        return true;
    }

    @GetMapping(value = "/member/phone")
    public Boolean validatePhone(@RequestParam(value = "phone") String phone) {

        if (memberService.getMemberByPhone(phone) != null) {
            return false;
        }
        return true;
    }

    @GetMapping(value = "/member/email")
    public Boolean validateEmail(@RequestParam(value = "email") String email) {

        if (memberService.getMemberByEmail(email) != null) {
            return false;
        }
        return true;
    }

    @GetMapping(value = "/member/edit/{id}/username")
    public Boolean validateEditUsername(@PathVariable(value = "id") Long id, @RequestParam(value = "username") String username) {

        if (memberService.getMemberByEditUsername(id, username) != null) {
            return false;
        }
        return true;
    }

    @GetMapping(value = "/member/edit/{id}/phone")
    public Boolean validateEditPhone(@PathVariable(value = "id") Long id, @RequestParam(value = "phone") String phone) {

        if (memberService.getMemberByEditPhone(id, phone) != null) {
            return false;
        }
        return true;
    }

    @GetMapping(value = "/member/edit/{id}/email")
    public Boolean validateEditEmail(@PathVariable(value = "id") Long id, @RequestParam(value = "email") String email) {

        if (memberService.getMemberByEditEmail(id, email) != null) {
            return false;
        }
        return true;
    }


    @GetMapping(value = "/member/geetest-init")
    public String geetesrInit() {

        GeetestLib gtSdk = new GeetestLib(GeetestConfig.getGeetest_id(), GeetestConfig.getGeetest_key(),
                GeetestConfig.isnewfailback());

        String resStr = "{}";

        //自定义userid
        String userid = "test";

        //自定义参数,可选择添加
        HashMap<String, String> param = new HashMap<String, String>();
        param.put("user_id", userid); //网站用户id
        param.put("client_type", "web"); //web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
        param.put("ip_address", "127.0.0.1"); //传输用户请求验证时所携带的IP

        //进行验证预处理
        int gtServerStatus = gtSdk.preProcess(param);

        redisTemplate.putCache("userid", userid);
        redisTemplate.putCache(gtSdk.gtServerStatusSessionKey, gtServerStatus);
        resStr = gtSdk.getResponseStr();
        return resStr;
    }

    @PostMapping(value = "/member/login")
    public Result<com.freesky.common.vo.portal.VOMember> login(@RequestBody VOMemberLoginRegist memberLoginRegist) {
        GeetestLib gtSdk = new GeetestLib(GeetestConfig.getGeetest_id(), GeetestConfig.getGeetest_key(), GeetestConfig.isnewfailback());
        String challenge = memberLoginRegist.getChallenge();
        String validate = memberLoginRegist.getValidate();
        String seccode = memberLoginRegist.getSeccode();
        int gt_server_status_code =  redisTemplate.getCacheObject(gtSdk.gtServerStatusSessionKey,int.class);

        String userid = redisTemplate.getCacheObject("userid",String.class);

        //自定义参数,可选择添加
        HashMap<String, String> param = new HashMap<String, String>();
        param.put("user_id", userid); //网站用户id
        param.put("client_type", "web"); //web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
        param.put("ip_address", "127.0.0.1"); //传输用户请求验证时所携带的IP

        int gtResult = 0;

        if (gt_server_status_code == 1) {
            //gt-server正常，向gt-server进行二次验证
            gtResult = gtSdk.enhencedValidateRequest(challenge, validate, seccode, param);
            System.out.println(gtResult);
        } else {
            // gt-server非正常情况下，进行failback模式验证
            System.out.println("failback:use your own server captcha validate");
            gtResult = gtSdk.failbackValidateRequest(challenge, validate, seccode);
            System.out.println(gtResult);
        }

        //先关闭极验
        com.freesky.common.vo.portal.VOMember voMember = memberService.userLogin(memberLoginRegist.getUserName(), memberLoginRegist.getUserPwd());

//        if (gtResult == 1) {
//            // 验证成功
//            voMember = loginService.userLogin(VOMemberLoginRegist.getUserName(), VOMemberLoginRegist.getUserPwd());
//        } else {
//            // 验证失败
//            voMember.setState(0);
//            voMember.setMessage("验证失败");
//        }
        return new ResultUtil<com.freesky.common.vo.portal.VOMember>().setData(voMember);
    }

    @GetMapping(value = "/member/login/check")
    public Result<com.freesky.common.vo.portal.VOMember> checkLogin(@RequestParam(value = "token",defaultValue = "") String token) {
        com.freesky.common.vo.portal.VOMember voMember = memberService.getUserByToken(token);
        return new ResultUtil<com.freesky.common.vo.portal.VOMember>().setData(voMember);
    }

    @GetMapping(value = "/member/logout")
    public Result<Object> logout(@RequestParam(value = "token",defaultValue = "") String token) {

        memberService.logout(token);
        return new ResultUtil<Object>().setData(null);
    }

    @PostMapping(value = "/member/register")
    public Result<Object> register(@RequestBody VOMemberLoginRegist memberLoginRegist,
                                   HttpServletRequest request) {

        GeetestLib gtSdk = new GeetestLib(GeetestConfig.getGeetest_id(), GeetestConfig.getGeetest_key(), GeetestConfig.isnewfailback());
        String challenge = memberLoginRegist.getChallenge();
        String validate = memberLoginRegist.getValidate();
        String seccode = memberLoginRegist.getSeccode();
        //从session中获取gt-server状态
        int gt_server_status_code = (Integer) request.getSession().getAttribute(gtSdk.gtServerStatusSessionKey);

        //从session中获取userid
        String userid = (String) request.getSession().getAttribute("userid");

        //自定义参数,可选择添加
        HashMap<String, String> param = new HashMap<String, String>();
        param.put("user_id", userid); //网站用户id
        param.put("client_type", "web"); //web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
        param.put("ip_address", "127.0.0.1"); //传输用户请求验证时所携带的IP

        int gtResult = 0;

        if (gt_server_status_code == 1) {
            //gt-server正常，向gt-server进行二次验证
            gtResult = gtSdk.enhencedValidateRequest(challenge, validate, seccode, param);
            System.out.println(gtResult);
        } else {
            // gt-server非正常情况下，进行failback模式验证
            System.out.println("failback:use your own server captcha validate");
            gtResult = gtSdk.failbackValidateRequest(challenge, validate, seccode);
            System.out.println(gtResult);
        }

        if (gtResult == 1) {
            // 验证成功
            int result = memberService.register(memberLoginRegist.getUserName(), memberLoginRegist.getUserPwd());
            if (result == 0) {
                return new ResultUtil<Object>().setErrorMsg("该用户名已被注册");
            } else if (result == -1) {
                return new ResultUtil<Object>().setErrorMsg("用户名密码不能为空");
            }
            return new ResultUtil<Object>().setData(result);
        } else {
            // 验证失败
            return new ResultUtil<Object>().setErrorMsg("验证失败");
        }
    }

    @PostMapping(value = "/member/image/upload")
    public Result<Object> imgaeUpload(@RequestBody VOCommon common) {

        String imgPath = memberService.imageUpload(common.getUserId(), common.getToken(), common.getImgData());
        return new ResultUtil<Object>().setData(imgPath);
    }
}
